package com.aitaoxue.palx.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap.Config;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;

import com.aitaoxue.palx.AppContext;

public class ImageUtil {
	private static final String TAG=ImageUtil.class.getSimpleName();
	
	//获得临时存储图片的路径
	public static File getImagePath() {
		long time = System.currentTimeMillis();
		
		Log.d(TAG, time+"");
		File path = AppContext.getInstance().getExternalFilesDir(
				Environment.DIRECTORY_PICTURES);
		String imagePath=null;
		
		File image = null;
		
		image = new File(path, time+".jpg");
		
		Log.d(TAG, "name: "+image.getAbsolutePath());

		return image;
	}

	//从原始图片加载合适的bitmap到内存中
	public static Bitmap compressImgFromFile(String imagePath,float ww,float hh) {
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;

		Bitmap bitmap = BitmapFactory.decodeFile(imagePath, options);
		options.inJustDecodeBounds = false;

		int w = options.outWidth;
		int h = options.outHeight;
		int scale = 1;

		if (w > h && w > ww) {
			scale = (int) (options.outWidth / ww);
		} else if (w < h && h > hh) {
			scale = (int) (options.outHeight / hh);
		}

		if (scale <= 0) {
			scale = 1;
		}

		options.inSampleSize = scale;

		options.inPreferredConfig = Config.ARGB_8888;
		options.inPurgeable = true;
		options.inInputShareable = true;

		bitmap = BitmapFactory.decodeFile(imagePath, options);

		return bitmap;
	}

	//将内存中的bitmap压缩后保存在文件中
	public static void compressBitmapToFile(String imagePath,Bitmap img,int size) {
		File file = new File(imagePath);

		if (file.exists()) {
			file.delete();
			try {
				file.createNewFile();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		int options = 100;
		img.compress(Bitmap.CompressFormat.JPEG, options, baos);
		while (baos.toByteArray().length / 1024 > size) {
			baos.reset();
			options -= 5;
			img.compress(Bitmap.CompressFormat.JPEG, options, baos);
		}

		try {
			FileOutputStream out = new FileOutputStream(file);
			out.write(baos.toByteArray());
			out.flush();
			out.close();
			baos.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}
